function getElementsByClassName(strClass, strTag, objContElm) {
  strTag = strTag || "*";
  objContElm = objContElm || document;
  var objColl = objContElm.getElementsByTagName(strTag);
  if (!objColl.length &&  strTag == "*" &&  objContElm.all) objColl = objContElm.all;
  var arr = new Array();
  var delim = strClass.indexOf('|') != -1  ? '|' : ' ';
  var arrClass = strClass.split(delim);
  for (var i = 0, j = objColl.length; i < j; i++) {
    var arrObjClass = objColl[i].className.split(' ');
    if (delim == ' ' && arrClass.length > arrObjClass.length) continue;
    var c = 0;
    comparisonLoop:
    for (var k = 0, l = arrObjClass.length; k < l; k++) {
      for (var m = 0, n = arrClass.length; m < n; m++) {
        if (arrClass[m] == arrObjClass[k]) c++;
        if (( delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
          arr.push(objColl[i]);
          break comparisonLoop;
        }
      }
    }
  }
  return arr;
}

function findCodeRegions(){
	return getElementsByClassName('RCode');
}


var buttonToggles = Object();
var codeBlockToButton = Object();

var initialize = function(event){
	var codeSection = Array();
	var codeSections = findCodeRegions();
	
	var node;
	for (var i=0; node=codeSections[i]; i++){
	    var toolBar = findToolbar(node);
	    var toggleBtn = firstRealChild(toolBar);
	    var content = findContent(node);
	    var rd = Math.floor(Math.random()*1000);
	   
	    content.id = rd;
		codeBlockToButton[rd] = toggleBtn;
		
	    toggleBtn.onclick = getSectionVisibilityToggle(rd,toggleBtn);
	}
}

var findToolbar = function(parentNode){
    var node2;
    for(var i = 0; node2=parentNode.childNodes[i];i++){
	if (node2.className == 'RControls')
	    return node2;
    }
    return null;
}

var findContent = function(parentNode){
	var node;
	for(var i=0;node=parentNode.childNodes[i];i++){
	    if (node.className == 'RCodeContent')
		return node;
	}
	return null;
}

var firstRealChild = function(parentNode){
	var node;
	for(var i =0;node=parentNode.childNodes[i];i++){
	    if (node.nodeType == 1){
		return node;
	    }
	}
	return null;
}

var getSectionVisibilityToggle = function(id,button){
   	var btn = button
    
    var toggleFunction = function(){
		if (buttonToggles[id]){
			showCodeBlock(id,btn);
		} else {
			hideCodeBlock(id,btn);
		}
	}
    
    return toggleFunction;
}

var hideCodeBlock = function(codeBlockId, button){
	$('#'+codeBlockId).hide("slow");	
	button.innerHTML = "Show";
	buttonToggles[codeBlockId] = true;
}


var showCodeBlock = function(codeBlockId, button){
	$('#'+codeBlockId).show("slow");	
	button.innerHTML = "Hide";
	buttonToggles[codeBlockId] = false;
}


var showAll_click = function(){
	for (var block in codeBlockToButton){
		var btn = codeBlockToButton[block]
		showCodeBlock(block,btn);
	}
}


var hideAll_click = function(){
	for (var block in codeBlockToButton){
		var btn = codeBlockToButton[block]
		hideCodeBlock(block,btn);
	}
}

